<?php
//首页显示
namespace Home\Controller;
use Think\Controller;
class PayController extends CommonController {
	function _initialize(){
		parent::_initialize();
		 vendor('Weixinpay.WxPayPubHelper');
		$user_id=session('user_id');
		if(!$user_id){
			$agreen_action=array('buy_now','notify_url','wxnotify');
			$action_name=ACTION_NAME;
			if(!in_array($action_name,$agreen_action)){
				$this->redirect('user/login');
			}
		}
		$config = array (	
				//应用ID,您的APPID。
				'app_id' => C('ali.ali_appid'),
				//商户私钥
				'merchant_private_key' => C('ali.merchant_private_key'),
				//异步通知地址
				'notify_url' => "http://www.58daiyan.com/pay/notify_url",
				//同步跳转
				'return_url' => "http://www.58daiyan.com/pay/return_url",
				//编码格式
				'charset' => "UTF-8",
				//签名方式
				'sign_type'=>"RSA2",
				//支付宝网关
				'gatewayUrl' => "https://openapi.alipay.com/gateway.do",
				//支付宝公钥,查看地址：https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
				'alipay_public_key' => C('ali.alipay_public_key'),
		);
		$this->alipay_config = $config;
		
	}
   /**
     * 购买流程：查看购物车，待付款订单 第一步
*/
    public function paymentOrder(){
    	
    	//收货地址
    	$this->address();
    	//订单商品
        $result=$this->orderInfo();
       
        if($result==null){
        	$this->redirect('cart/cart_list');
        }
        //优惠券
		$coupon=M('coupon');
		$coupon_type=M('coupon_type');
		$uid=session('user_id');
		$rs_coupon=$coupon
				->field('coupon_type_id,start_time,end_time')
				->where("uid=$uid and state=1")
				->group('coupon_type_id')
				->select();
		$coupons_i=0;
		$coupon_shop_ids=session('cart_list_id');
		//dump($rs_coupon);
		
		foreach($result as $key =>$value){
			foreach($value as $k =>$v){
				$new_coupon_shop_ids[]=$v['shop_id'];
			}
		}
		
		$new_coupon_shop_ids=implode(',',$new_coupon_shop_ids);
		
		$rs=M('coupon_goods')->field('coupon_type_id')->where("goods_id in ($new_coupon_shop_ids)")->group('coupon_type_id')->select();
		foreach($rs as $key =>$value){
			$new_rs[]=$value['coupon_type_id'];
		}
		//dump($new_rs);
    	$new_coupons;
		foreach($rs_coupon as $key=>$value){
			
			
    		$nowtime=time();
    		$rs_coupon_type=$coupon_type->find($value['coupon_type_id']);
			
    		//先判断是否是下单商品可使用的优惠券
    		if(in_array($rs_coupon_type['coupon_type_id'],$new_rs)){
				$start_time=strtotime($rs_coupon_type['start_time']);
    		    $end_time=strtotime($rs_coupon_type['end_time']);
	    		if($start_time<=$nowtime && $end_time>=$nowtime){
	    			//计算可用优惠券总价格
	    			$rs_coupon_goods=M('coupon_goods')->where("coupon_type_id=".$value['coupon_type_id'])->select();
	    			$count_price=0;
	    			$new_coupon_shop_ids=explode(',',$new_coupon_shop_ids);
	    			foreach($rs_coupon_goods as $key=>$value){
	    				if(in_array($value['goods_id'],$new_coupon_shop_ids)){
	    					$goods_ids[]=$value['goods_id'];
	    				}
	    			}
	    			foreach($result as $key =>$value){
						foreach($value as $k =>$v){
							if(in_array($v['shop_id'],$goods_ids)){
		    					$count_price=$count_price+($v['price']*$v['num']);
		    				}
						}
					}
					//判断价格
	    			if($rs_coupon_type['at_least']==0||($rs_coupon_type['at_least']!=0&&$rs_coupon_type['at_least']<=$count_price)){
		    			$new_coupons[$coupons_i]=$value;
		    			$new_coupons[$coupons_i]['coupon_name']=$rs_coupon_type['coupon_name'];
		    			$new_coupons[$coupons_i]['coupon_type_id']=$rs_coupon_type['coupon_type_id'];
		    			$new_coupons[$coupons_i]['at_least']=$rs_coupon_type['at_least'];
		    			$new_coupons[$coupons_i]['money']=$rs_coupon_type['money'];
		    			if($rs_coupon_type['at_least']!=0){
		    				$new_coupons[$coupons_i]['xcy']='满'.$rs_coupon_type['at_least'].'元,减'.$rs_coupon_type['money'].'元';
		    			}else{
		    				$new_coupons[$coupons_i]['xcy']='无限制,减'.$rs_coupon_type['money'].'元';
		    			}
		    			$coupons_i++;
	    			}
	    		}
    		}
		}
		
        $this->assign('new_coupons',$new_coupons);
        $this->assign('result',$result);
        $this->display();
    }

    /**
     * 待付款订单需要的数据
    */
    public function orderInfo()
    {
    	$user_id=session('user_id');
   		$users_address=M('users_address');
   		$useraddress=$users_address->where('user_id='.$user_id.' and is_default=1')->find();
   		$city_id=$useraddress['city'];
   		
       $cart_list_id=session('cart_list_id');
      
       $cart=M('cart');
       $shop_sku=M('shop_sku');
       $shop=M('shop');
       if(is_array($cart_list_id)){
       		$new_cart;
       		foreach($cart_list_id as $key =>$v){
       			$new_cart[$key]=$v['cart_id'];
       		}
       		$new_cart=implode(',',$new_cart);
       		$map['cart_id']  = array('in',$new_cart);
       		$cart_list=$cart->where($map)->select();
       	}else{
       		$cart_list=$cart->where('cart_id='.$cart_list_id)->select();
     	}
       	$result =   array();
       
		foreach($cart_list as $key => $v){
			
			$rs_shop=$shop->find($v['shop_id']);
			$v['freight']=get_freight($v['shop_id'],$city_id,$v['num']);
			//抵扣券优惠
			$shop_id=$v['shop_id'];
            $invoice=get_web_invoice();
			$start_time=time()-60*60*24*$invoice['web_diyong'];
			$daiyan_info=M('daiyan')->where("uid=$user_id and shop_id=$shop_id and time>$start_time")->find();
			
			if($daiyan_info){
				$v['daiyan_sale']=$rs_shop['dikouquan'];
			}else{
				$v['daiyan_sale']=0;
			}
			if($v['sku_id']!=0){
				$rs_shop_sku=$shop_sku->where('sku_id='.$v['sku_id'])->find();
				$v['sku_spec']=$rs_shop_sku['sku_spec'];
				$v['sku_style']=$rs_shop_sku['sku_style'];
			}
			$v['url']=U('shop/index',array('id'=>$v['shop_id']));
			$v['id']=$v['shop_id'].','.$v['sku_id'];
			$v['oprice']=$rs_shop['oprice'];
			if($v['recommend_id']){
				$v['redenvelope']=$rs_shop['redenvelope'];
			}
			if($v['select']==1){
				$count['num']=$count['num']+$v['num'];
				$count['price']=$count['price']+($v['num']*$v['price'])-($v['num']*$v['daiyan_sale']);
			}
			
			$result[$v['store_id']][] =$v;
		}
		return $result;
       
    }
    
     public function address(){
   		$user_id=session('user_id');
   		$users=M('users');
   		$users_address=M('users_address');
        if($user_id){
        	$userinfo=$users->find($user_id);
        	$useraddress=$users_address->where('user_id='.$user_id)->limit(5)->select();
        	foreach($useraddress as $key=>$value){
				$province=getProvinceInfo($value['province']);
				$city=getCityInfo($value['city']);
				$district=getDistrictInfo($value['district']);
				$useraddress[$key]['province']=$province['province_name'];
				$useraddress[$key]['city']=$city['city_name'];
				$useraddress[$key]['district']=$district['district_name'];
			}
        	$this->assign('useraddress',$useraddress);
        }
    }
    
    function buy_now(){
    	$user_id=session('user_id');
    	$cart_list_id=session('cart_list_id');
    	if($user_id&&$cart_list_id){
    		$this->ajax_r('1','','商品获取成功，正在跳转....');
    	}
    	if($user_id==null){
    		$this->ajax_r('2','','未登录....');
    	}
    	if($cart_list_id==null){
    		$this->ajax_r('2','','代码问题，请联系管理员...');
    	}
    }
    //礼品领取
    function lipin(){
    	$data=I('get.');
    	//收货地址
    	$this->address();
    	//商品
    	$shop_info=M('shop')->find($data['recommend_shop_id']);
    	
    	$this->assign('shop_info',$shop_info);
    	$this->assign('info',$data);
    	$this->display();
    }
    //生成订单 以下字段默认
    //支付单号 
	//$data['pay_sn']
	//支付方式名称代码
	//$data['payment_code']
	//支付(付款)时间
	//$data['payment_time']
	//订单完成时间
	//$data['finnshed_time']
	//预存款支付金额
	//$data['pd_amount']
	//评价状态 0未评价，1已评价
	//$data['evaluation_state']
	//订单状态：0(已取消)10(默认):未付款;20:已付款;30:已发货;40:已收货;
	//$data['order_state']
	//退款状态:0是无退款,1是部分退款,2是全部退款
	//$data['refund_state']
	//锁定状态:0是正常,大于0是锁定,默认是0
	//$data['lock_state']
	//退款金额
	//$data['refund_amount']
	//延迟时间,默认为0
	//$data['delay_time']
	//物流单号
	//$data['shipping_code']
	//物流商家
	//$data['shipping_name']
    function generate_order(){
    	
    	//统计商品
    	$result= $this->orderInfo();
    	
    	$user_id=session('user_id');
		$user_info=M('users')->find($user_id);
		if($user_info['phone']==null){
			$this->ajax_r(0,'','请先去个人中心-关联账户中绑定手机');
		}
    	//总订单号
    	$order_cn = $this->build_order_no();
    	
		//获取收货地址
		$user_address=get_user_address($user_id);
		if($user_address==null){
			$this->ajax_r(0,'','请添加收货地址');
		}
    	if($result&&$user_id){
    		foreach($result as $key=>$value){
    			$data=array();
	    		$store_info=get_store($key);
	    		$count_price=0;
	    		$count_fee=0;
	    		foreach($value as $k=>$v){
	    			$count_price=$count_price+$v['price']*$v['num'];
	    			$count_fee=$count_fee+$v['freight'];
	    		}
	    		
		    	//订单总编号
				$data['order_cn']=$order_cn; 
				$order_sn = $this->build_order_no();
				//订单子编号
				$data['order_sn']=$order_sn;
				//卖家店铺id
				$data['store_id']=$key;
				//卖家店铺名称
				$data['store_name']=$store_info['title'];
				//买家id
				$data['buyer_id']=$user_id;
				//买家收货地址ID
				$data['buyer_address_id']=$user_address['address_id'];
				//收货姓名
				$data['buyer_name']=$user_address['consigner'];
				//收货省
				$data['buyer_province']=$user_address['province'];
				//收货市
				$data['buyer_city']=$user_address['city'];
				//收货区域
				$data['buyer_district']=$user_address['district'];
				//收货地址
				$data['buyer_address']=$user_address['address'];
				//收货手机
				$data['buyer_mobile']=$user_address['mobile'];
				//收货电话
				$data['buyer_phone']=$user_address['phone'];
				//收货邮编
				$data['buyer_zip_code']=$user_address['zip_code'];
				//订单生成时间
				$data['add_time']=time();
				//1WEB2mobile
				$data['order_from']=1;
				//商品总价格
				$data['goods_amount']=$count_price;
				//订单总价格
				$data['order_amount']=$count_price+$count_fee;
				//运费
				$data['shipping_fee']=$count_fee;
				//默认红包
				$data['daiyan_sale']=0;
				
				foreach($value as $k1=>$v1){
					//团购设置
					$shop_info=M('shop')->find($v1['shop_id']);
                    if($shop_info['is_crowdfunding']=='1'){
                        $data['order_type']=2;
                    }
                    //免发货设置
                    $data['mian_send']=$shop_info['mian_send'];
					if($v1['tuanselect']==1){
						$data['tuanselect']=1;
						$data['tuan_is_first_id']=$v1['tuan_id'];
						$tuan_rs=$shop_info;
						$data['tuannum']=$tuan_rs['tuan_num'];
						if($v1['tuan_id']){
							$count_num=get_tuan($v1['tuan_id']);
							if($count_num>=$data['tuannum']){
								$this->ajax_r(0,$data['order_cn'],'该团已满！');
							}
						}
						$return=M('order')->find($v1['tuan_id']);
						if($return['refund_state']>0){
							$this->ajax_r(0,$data['order_cn'],'该团已过期！');
						}
					}
					//抵扣券优惠
					$shop_id=$v1['shop_id'];
                    $invoice=get_web_invoice();
					$start_time=time()-60*60*24*$invoice['web_diyong'];
					$daiyan_info=M('daiyan')->where("uid=$user_id and shop_id=$shop_id and time>$start_time")->find();
					
					if($daiyan_info){
						$data['daiyan_sale']=$data['daiyan_sale']+$shop_info['dikouquan']*$v['num'];
					}
					
					
				}
				if($_POST){
					//是否开发票
					$data['invoice_status']=I('post.invoice_status');
					//发票抬头
					$data['invoice_title']=I('post.invoice_title');
					//发票类型
					$data['invoice_content']=I('post.invoice_content');
					//留言
					$data['leavemessage']=I('post.leavemessage');
					//优惠券种类ID
					$data['coupon']=I('post.coupon');
					$order=M('order');
					$cart=M('cart');
					$order_goods=M('order_goods');
					//开启事物
					$order->startTrans(); 
					$cart->startTrans(); 
					$order_goods->startTrans(); 
					//判断条件
					$falg=true;
					$rs_order=$order->add($data);
					if(!$rs_order){
						$falg=false;
					}
					foreach($value as $k=>$v){
		    			$order_good['order_id']=$rs_order;
		    			$order_good['goods_id']=$v['shop_id'];
		    			$order_good['goods_name']=$v['shop_name'];
		    			$order_good['goods_price']=$v['price'];
		    			$order_good['goods_num']=$v['num'];
		    			
		    			$order_good['goods_image']=$v['shop_picture'];
		    			$order_good['goods_pay_price']=$v['price']*$v['num'];
		    			$order_good['goods_sku']=$v['sku_id'];
		    			$order_good['goods_sku_spec']=$v['sku_spec'];
		    			$order_good['goods_sku_style']=$v['sku_style'];
		    			
		    			
		    			//代言奖励写入
		    			$order_shop_id=$v['shop_id'];
		    			$invoice=get_web_invoice();
		    			$start_time=time()-60*60*24*$invoice['web_diyong'];
						$order_daiyan_info=M('daiyan')->where("uid=$user_id and shop_id=$order_shop_id and time>".$start_time)->find();
					
						if($order_daiyan_info&&$order_daiyan_info['bid']!=$order_daiyan_info['uid']){
							$recommend_id=$order_daiyan_info['bid'];
						}else{
							$recommend_id=0;
						}
		    			$order_good['recommend_id']=$recommend_id;
		    			if($recommend_id>0){
		    				$order_shop_info=M('shop')->find($v['shop_id']);
		    				$order_good['recommend_type']=$order_shop_info['envelope_type'];
		    				//红包奖励
		    				if($order_shop_info['envelope_type']==0){
		    					$order_good['recommend_price']=$order_shop_info['redenvelope']*$v['num'];
		    					$order_good['recommend_shop_id']=0;
		    					$order_good['recommend_shop_num']=0;
		    				}
		    				//礼品奖励
		    				if($order_shop_info['envelope_type']==1){
		    					$order_good['recommend_price']=0;
		    					$order_good['recommend_shop_id']=$order_shop_info['envelope_product_id'];
		    					if($order_shop_info['envelope_product_type']==0){
		    						$order_good['recommend_shop_num']=1;
		    					}
		    					if($order_shop_info['envelope_product_type']==1){
		    						$order_good['recommend_shop_num']=$v['num'];
		    					}
		    					
		    				}
		    				
		    			}
		    			
		    		
		    			
		    			$order_good['store_id']=$v['store_id'];
		    			$order_good['buyer_id']=$user_id;
		    			$order_good['goods_type']=1;
		    			$order_good['freight']=$v['freight'];
		    			
		    			$rs_good=$order_goods->add($order_good);
		    			if(!$rs_good){
		    				
							$falg=false;
						}
		    			$rs_cart=$cart->delete($v['cart_id']);
		    			if(!$rs_cart){
		    			
							$falg=false;
						}
		    		}
		    	}
			}
			if($falg){
				$order->commit(); 
				$cart->commit(); 
				$order_goods->commit(); 
				//添加订单信息到redis监控
				addredis($data['order_cn']);
				$this->ajax_r(1,$data['order_cn'],'下单成功');
			}else{
				$order->rollback(); 
				$cart->rollback(); 
				$order_goods->rollback(); 
				$this->ajax_r(0,'','下单失败');
			}
			
		}
    }
    
    
     //生成礼品订单 以下字段默认
    //支付单号 
	//$data['pay_sn']
	//支付方式名称代码
	//$data['payment_code']
	//支付(付款)时间
	//$data['payment_time']
	//订单完成时间
	//$data['finnshed_time']
	//预存款支付金额
	//$data['pd_amount']
	//评价状态 0未评价，1已评价
	//$data['evaluation_state']
	//订单状态：0(已取消)10(默认):未付款;20:已付款;30:已发货;40:已收货;
	//$data['order_state']
	//退款状态:0是无退款,1是部分退款,2是全部退款
	//$data['refund_state']
	//锁定状态:0是正常,大于0是锁定,默认是0
	//$data['lock_state']
	//退款金额
	//$data['refund_amount']
	//延迟时间,默认为0
	//$data['delay_time']
	//物流单号
	//$data['shipping_code']
	//物流商家
	//$data['shipping_name']
     function generate_order2(){
    	$order_data=I('post.');
    	$user_id=session('user_id');
    	//匹配礼品领取人 与登陆用户是否一个
    	$tuij_order_good=M('order_goods')->find($order_data['rec_id']);
    	$tuij_order=M('order')->find($tuij_order_good['order_id']);
    	if($tuij_order['order_state']<20){
    		$this->ajax_r(0,'','该推荐用户订单未支付.');
    	}
    	if($tuij_order_good['recommend_id']!=$user_id){
    		$this->ajax_r(0,'','该订单 推荐用户不是您，不可领取礼品？');
    	}
    	if($tuij_order_good['recommend_orderid']>0){
    		$this->ajax_r(0,'','礼品已领取');
    	}
    	
    	//礼品
    	$result= M('shop')->find($order_data['recommend_shop_id']);
    	$user_info=M('users')->find($user_id);
		if($user_info['phone']==null){
			$this->ajax_r(0,'','请先去个人中心-关联账户中绑定手机');
		}
    	//总订单号
    	$order_cn = $this->build_order_no();
    	
		//获取收货地址
		$user_address=get_user_address($user_id);
		if($user_address==null){
			$this->ajax_r(0,'','请添加收货地址');
		}
    	if($result&&$user_id){
    			$data=array();
    			$store_info=get_store($result['store_id']);
	    		//订单总编号
				$data['order_cn']=$order_cn; 
				$order_sn = $this->build_order_no();
				//订单子编号
				$data['order_sn']=$order_sn;
				$data['pay_sn']=$order_sn;
				//卖家店铺id
				$data['store_id']=$result['store_id'];
				//卖家店铺名称
				$data['store_name']=$store_info['title'];
				//买家id
				$data['buyer_id']=$user_id;
				//买家收货地址ID
				$data['buyer_address_id']=$user_address['address_id'];
				//收货姓名
				$data['buyer_name']=$user_address['consigner'];
				//收货省
				$data['buyer_province']=$user_address['province'];
				//收货市
				$data['buyer_city']=$user_address['city'];
				//收货区域
				$data['buyer_district']=$user_address['district'];
				//收货地址
				$data['buyer_address']=$user_address['address'];
				//收货手机
				$data['buyer_mobile']=$user_address['mobile'];
				//收货电话
				$data['buyer_phone']=$user_address['phone'];
				//收货邮编
				$data['buyer_zip_code']=$user_address['zip_code'];
				//订单生成时间
				$data['add_time']=time();
				//1WEB2mobile
				$data['order_from']=1;
				//商品总价格
				$data['goods_amount']=0;
				//订单总价格
				$data['order_amount']=0;
				//运费
				$data['shipping_fee']=0;
				$data['order_state']='20';
				$data['payment_code']='礼品领取';
				$data['payment_time']=time();
				$data['order_type']=1;
				$data['daiyan_sale']=0;
				if($_POST){
					//留言
					$data['leavemessage']=I('post.leavemessage');
					$order=M('order');
					$cart=M('cart');
					$order_goods=M('order_goods');
					//开启事物
					$order->startTrans(); 
					$cart->startTrans(); 
					$order_goods->startTrans(); 
					//判断条件
					$falg=true;
					$rs_order=$order->add($data);
                 
					if(!$rs_order){
						$falg=false;
					}
					
	    			$order_good['order_id']=$rs_order;
	    			$order_good['goods_id']=$result['id'];
	    			$order_good['goods_name']=$result['title'];
	    			$order_good['goods_price']=0;
	    			$order_good['goods_num']=$order_data['recommend_shop_num'];
	    			
	    			$order_good['goods_image']=$result['image'];
	    			$order_good['goods_pay_price']=0;
	    			$order_good['goods_sku']=0;
	    			$order_good['goods_sku_spec']=0;
	    			$order_good['goods_sku_style']=0;
	    			$order_good['store_id']=$result['store_id'];
	    			$order_good['buyer_id']=$user_id;
	    			$order_good['goods_type']=5;
	    			$order_good['freight']=0;
	    			$rs_good=$order_goods->add($order_good);
                 
	    			if(!$rs_good){
	    				$falg=false;
					}
	    		}
			
			if($falg){
				$order_g_info['rec_id']=$order_data['rec_id'];
				$order_g_info['recommend_orderid']=$rs_order;
				M('order_goods')->save($order_g_info);
				$order->commit(); 
				$cart->commit(); 
				$order_goods->commit(); 
			
				$this->ajax_r(1,$data['order_cn'],'领取成功');
			}else{
				$order->rollback(); 
				$cart->rollback(); 
				$order_goods->rollback(); 
				$this->ajax_r(0,'','领取失败');
			}
			
		}
    }
    
    
    public function paychoose(){
    	$alipay=get_alipay_options();
    	
    	$wchat=get_wchat_options();
    	
    	$where['order_sn']=$_GET['order_cn'];
		$where['order_cn']=$_GET['order_cn'];
		$where['_logic'] = 'OR';
		$order_info=M('order')->where($where)->find();
		
    	$order_cn=I('get.order_cn');
    	$tuanselect=0;
    	$status=get_order_status($order_cn,'10');
    	if($status){
    		$order=M('order');
	    	$result=$order->where('order_cn='.$order_cn)->select();
	    	if($result){
	    		foreach($result as $key=>$value){
	    			$time=$value['add_time'];
	    			if($value['coupon']!=null){
	    				$youhui_price=get_coupon_price($value['buyer_id'],$value['coupon']);
	    			}
	    			$name=$value['buyer_name'];
	    			$tuanselect=$tuanselect+$value['tuanselect'];
	    			$count_price=$count_price+$value['order_amount']-$value['daiyan_sale']-$youhui_price;
		    	}
	    	}else{
	    		
	    		$result=$order->where('order_sn='.$order_cn)->find();
	    		$youhui_price=get_coupon_price($result['buyer_id'],$result['coupon']);
	    		$count_price=$result['order_amount']-$result['daiyan_sale']-$youhui_price;
	    		$time=$result['add_time'];
	    		$tuanselect=$tuanselect+$result['tuanselect'];
	    		$name=$result['buyer_name'];
	    	}
	    	
	    	$this->assign('tuanselect',$tuanselect);
	    	$this->assign('count_price',$count_price);
	    	$this->assign('time',$time);
	    	$this->assign('name',$name);
	    	$this->assign('alipay',$alipay);
	    	$this->assign('wchat',$wchat);
	    	$this->assign('order_id',$order_info['order_id']);
	    	if($count_price<=0){
	    		update_order_status($_GET['order_cn'], $_GET['order_cn'],'20','无需支付');
	    		$this->success('支付成功！','/user/order_info/order/'.$_GET['order_cn'],5);
	    	}else{
	    		$this->display();
	    	}
	    	
    	}else{
    		$this->error('订单状态不正确，请检查！','/user/order_info/id/'.$order_info['order_id'],5);
    	}
    	
    }
    
    public function build_order_no()
    {
        $no = date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
        //检测是否存在
        $db = M('order');
        $info = $db->where(array('order_sn'=>$no))->find();
        (!empty($info)) && $no = $this->build_order_no();
        return $no;
        
    }
    
    function wchatpay(){
    	
    	$order_cn=I('get.order_cn');
		
		$status=get_order_status($order_cn,'10');
    	if($status){
    		$order=M('order');
	    	$result=$order->where('order_cn='.$order_cn)->select();
	    	if($result){
				
	    		foreach($result as $key=>$value){
					$order_status=$this->orderQuery2($value['order_cn']);
					$order_status2=$this->orderQuery2($value['order_sn']);
					if($order_status||$order_status2){
						$this->success('该订单已支付成功！');
					}
	    			$time=$value['add_time'];
	    			if($value['coupon']!=null){
	    				$youhui_price=get_coupon_price($value['buyer_id'],$value['coupon']);
	    			}
	    			$count_price=$count_price+$value['order_amount']-$value['daiyan_sale']-$youhui_price;
		    	}
	    	}else{
	    		
	    		$result=$order->where('order_sn='.$order_cn)->find();
				$order_status=$this->orderQuery2($result['order_cn']);
				$order_status2=$this->orderQuery2($result['order_sn']);
				if($order_status||$order_status2){
					$this->success('该订单已支付成功！');
				}
	    		$youhui_price=get_coupon_price($result['buyer_id'],$result['coupon']);
	    		$count_price=$result['order_amount']-$result['daiyan_sale']-$youhui_price;
	    		
	    	}
	    	//使用统一支付接口
	        $unifiedOrder = new \UnifiedOrder_pub();
	 
	        
	        //设置统一支付接口参数
	        //设置必填参数
			//生成微信唯一订单号
            $new_order_cn=$order_cn.'_'.time();
            $ls_order['weixin_oreder']=$new_order_cn;
            echo $new_order_cn;
            M('order')->where("order_cn=$order_cn or order_sn=$order_cn")->save($ls_order);
            $order_cn=$new_order_cn;
	        $unifiedOrder->setParameter("body","悟能代言商城");//商品描述
	        //自定义订单号，此处仅作举例
			$unifiedOrder->setParameter("out_trade_no",$order_cn);//商户订单号 
	        $unifiedOrder->setParameter("total_fee",$count_price*100);//总金额
	        $unifiedOrder->setParameter("notify_url",'http://www.58daiyan.com/pay/wxnotify');//通知地址
	        $unifiedOrder->setParameter("trade_type","NATIVE");//交易类型
	        //非必填参数，商户可根据实际情况选填
	        //$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号  
	        //$unifiedOrder->setParameter("device_info","XXXX");//设备号 
	        //$unifiedOrder->setParameter("attach","XXXX");//附加数据 
	        //$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
	        //$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间 
			//$unifiedOrder->setParameter("goods_tag","");//商品标记 
			//$unifiedOrder->setParameter("openid","19405");//用户标识
	        //$unifiedOrder->setParameter("product_id","XXXX");//商品ID
	        //获取统一支付接口结果
	        $unifiedOrderResult = $unifiedOrder->getResult();
			//var_dump($unifiedOrder);
	        //商户根据实际情况设置相应的处理流程
	        if ($unifiedOrderResult["return_code"] == "FAIL") 
	        {
	            //商户自行增加处理流程
	            echo "通信出错：".$unifiedOrderResult['return_msg']."<br>";
	        }
	        elseif($unifiedOrderResult["result_code"] == "FAIL")
	        {
	            //商户自行增加处理流程
	            echo "错误代码：".$unifiedOrderResult['err_code']."<br>";
	            echo "错误代码描述：".$unifiedOrderResult['err_code_des']."<br>";
	        }
	        elseif($unifiedOrderResult["code_url"] != NULL)
	        {
	            //从统一支付接口获取到code_url(二维码)
	            $code_url = $unifiedOrderResult["code_url"];
	            //商户自行增加处理流程
	            //......
	        }

	        $this->assign('out_trade_no',$new_order_cn);
	        $this->assign('code_url',$code_url);
	        $this->assign('unifiedOrderResult',$unifiedOrderResult);
	    	$this->assign('count_price',$count_price);
    		$this->display();
    	}else{
    		$this->error('订单状态不正确，请检查！','/user/center',5);
    	}
    	
    }
    public function wxnotify()
    {
        //使用通用通知接口
        $notify = new \Notify_pub();
        //存储微信的回调
       // $xml = $GLOBALS['HTTP_RAW_POST_DATA'];
		$xml = file_get_contents('php://input');
        $notify->saveData($xml);
        // var_dump($xml);
        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if($notify->checkSign() == FALSE){
            $notify->setReturnParameter("return_code","FAIL");//返回状态码
            $notify->setReturnParameter("return_msg","签名失败");//返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;
        $parameter = $notify->xmlToArray($xml); 
        $out_trade_no=$parameter['out_trade_no'];
        $out_trade_no=explode('_',$out_trade_no);
        $out_trade_no=$out_trade_no[0];
        //==商户根据实际情况设置相应的处理流程，此处仅作举例=======
         
        //以log文件形式记录回调信息
        //         $log_ = new Log_();
        $log_name= __ROOT__."/notify_url.log";//log文件路径
         
        log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");
         
        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL") {
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name,"【通信出错】:\n".$xml."\n");
                echo 'error'; 
            }
            elseif($notify->data["result_code"] == "FAIL"){
                //此处应该更新一下订单状态，商户自行增删操作
                log_result($log_name,"【业务出错】:\n".$xml."\n");
                echo 'error'; 
            }
            else{
            	
                //此处应该更新一下订单状态，商户自行增删操作
                $res=$notify->data["result_code"];
    			switch($res){
    				case 'SUCCESS';
    					$status=get_order_status($out_trade_no,'10');
		    			if($status){
		    				update_order_status($out_trade_no, $out_trade_no,'20','微信');	
		    			}
		    			log_result($log_name,"【支付成功】:\n".$xml."\n");
		    			echo 'SUCCESS';
		    			break;
    				case 'NOTPAY';
    					echo 'NOTPAY';
		    			break;
    				default:
    					echo 'ERROR';
		    			break;
    			}
                
                
               
              
            }
             
         
        }
    }
    
     //查询订单
    public function orderQuery()
    {  
      
    	if (!isset($_POST["out_trade_no"]))
    	{
    		$out_trade_no = " ";
    	}else{
    	    $out_trade_no = $_POST["out_trade_no"];
    		//使用订单查询接口
    		$orderQuery = new \OrderQuery_pub();
    		//设置必填参数
    		//appid已填,商户无需重复填写
    		//mch_id已填,商户无需重复填写
    		//noncestr已填,商户无需重复填写
    		//sign已填,商户无需重复填写
    		$orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号 
    		//非必填参数，商户可根据实际情况选填
    		//$orderQuery->setParameter("sub_mch_id","XXXX");//子商户号  
    		//$orderQuery->setParameter("transaction_id","XXXX");//微信订单号
    		
    		//获取订单查询结果
    		$orderQueryResult = $orderQuery->getResult();
    		
    		//商户根据实际情况设置相应的处理流程,此处仅作举例
    		if ($orderQueryResult["return_code"] == "FAIL") {
    			$this->error($out_trade_no);
    		}
    		elseif($orderQueryResult["result_code"] == "FAIL"){
    			$this->error($out_trade_no);
    		}
    		else{
    			$res=$orderQueryResult["trade_state"];
    			switch($res){
    				case 'SUCCESS';
    					$status=get_order_status($out_trade_no,'10');
		    			if($status){
		    				update_order_status($out_trade_no, $orderQueryResult["transaction_id"],'20','微信');
		    				//dump($orderQueryResult);
		    			}
		    			echo 'SUCCESS';
		    			break;
    				case 'NOTPAY';
    					echo 'NOTPAY';
		    			break;
    				default:
    					echo 'ERROR';
		    			break;
    			}
    			
             
    		}	
    	}
    }
	 //查询订单
    public function orderQuery2($trade_no)
    {  
		$out_trade_no = $trade_no;
		//使用订单查询接口
		$orderQuery = new \OrderQuery_pub();
		//设置必填参数
		//appid已填,商户无需重复填写
		//mch_id已填,商户无需重复填写
		//noncestr已填,商户无需重复填写
		//sign已填,商户无需重复填写
		$orderQuery->setParameter("out_trade_no","$out_trade_no");//商户订单号 
		//非必填参数，商户可根据实际情况选填
		//$orderQuery->setParameter("sub_mch_id","XXXX");//子商户号  
		//$orderQuery->setParameter("transaction_id","XXXX");//微信订单号
		
		//获取订单查询结果
		$orderQueryResult = $orderQuery->getResult();
		
		//商户根据实际情况设置相应的处理流程,此处仅作举例
		if ($orderQueryResult["return_code"] == "FAIL") {
			return false;
			die;
		}
		elseif($orderQueryResult["result_code"] == "FAIL"){
			return false;
			die;
		}
		else{
			$res=$orderQueryResult["trade_state"];
			switch($res){
				case 'SUCCESS';
					$status=get_order_status($out_trade_no,'10');
					if($status){
						update_order_status($out_trade_no, $orderQueryResult["transaction_id"],'20','微信');
						//dump($orderQueryResult);
					}
					return true;
					break;
				case 'NOTPAY';
					return false;
					break;
				default:
					return false;
					break;
			}
			
		 
		}	
    	
    }
    function alipay(){
    	$order_cn=I('get.order_cn');
    	$count_price=get_count_price($order_cn);
    	$status=get_order_status($order_cn,'10');
    	$alipay=get_alipay_options();
    	if($status&&$alipay['alipay_is_use']=='on'){
    		//建立请求
			Vendor('AlipaySdk.AopSdk');
			//构造参数  
			
    		$alipay_config=$this->alipay_config;
			
			$aop = new \AopClient ();		
		    $aop->gatewayUrl ="https://openapi.alipay.com/gateway.do";
			$aop->appId = $alipay_config['app_id'];
		    $aop->rsaPrivateKey =$alipay_config['merchant_private_key'];
		    $aop->apiVersion = '1.0';
		    $aop->signType = 'RSA2';
		    $aop->postCharset= 'utf-8';
		    $aop->format='json';
		    $aop->alipayrsaPublicKey =$alipay_config['alipay_public_key'];
			$request = new \AlipayTradePagePayRequest ();
			$request->setReturnUrl('http://www.58daiyan.com/pay/return_url');
			$request->setNotifyUrl('http://www.58daiyan.com/pay/notify_url');
            $count_price=number_format($count_price,2,".","");
			$request->setBizContent('{"product_code":"FAST_INSTANT_TRADE_PAY","out_trade_no":"'.$order_cn.'","subject":"'.$order_cn.'-58代言","total_amount":"'.$count_price.'","body":"58代言商城"}');

     		$result = $aop->pageExecute ($request);

    		echo $result;
		}else{
    		$this->error('订单状态错误，或者该支付方式未开启','/index/index',5);
    	}
    }
    //支付宝异步处理
    function notify_url(){
    	$alipay_config=$this->alipay_config;
    	//建立请求
		Vendor('AlipaySdk.AopSdk');
    	$arr=$_POST;
		$aop = new \AopClient();
		$aop->alipayrsaPublicKey = $alipay_config['alipay_public_key'];
		$result = $aop->rsaCheckV1($arr,$alipay_config['alipay_public_key'],$alipay_config['sign_type']);
		
		if($result) {//验证成功
			/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			//请在这里加上商户的业务逻辑程序代
			//——请根据您的业务逻辑来编写程序（以下代码仅作参考）——
			//获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表
			$out_trade_no = $_POST['out_trade_no'];//商户订单号
			$trade_no = $_POST['trade_no'];//支付宝交易号
			$trade_status = $_POST['trade_status'];//交易状态
			if($_POST['trade_status'] == 'TRADE_FINISHED') {
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
					//如果有做过处理，不执行商户的业务程序
					update_order_status($out_trade_no,$trade_no,'20','支付宝');	
				//注意：
				//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
		
		        //调试用，写文本函数记录程序运行情况是否正常
		        //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
		    }
		    else if ($_POST['trade_status'] == 'TRADE_SUCCESS') {
				//判断该笔订单是否在商户网站中已经做过处理
					//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
					//请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
					//如果有做过处理，不执行商户的业务程序
					update_order_status($out_trade_no,$trade_no,'20','支付宝');	
							
				//注意：
				//付款完成后，支付宝系统发送该交易状态通知
				//调试用，写文本函数记录程序运行情况是否正常
		        //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
		    }
		
			//——请根据您的业务逻辑来编写程序（以上代码仅作参考）——
		        
			echo "success";		//请不要修改或删除
			
			/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		}
		else {
		    //验证失败
		    echo "fail";
		
		    //调试用，写文本函数记录程序运行情况是否正常
		    //logResult("这里写入想要调试的代码变量值，或其他运行的结果记录");
		}
    }
    
    //支付宝同步处理
    function return_url(){
    	$alipay_config=$this->alipay_config;
		//建立请求

		Vendor('AlipaySdk.AopSdk');
    	$arr=I('get.');
		$aop = new \AopClient();
		$aop->alipayrsaPublicKey = $alipay_config['alipay_public_key'];
		$result = $aop->rsaCheckV1($arr,$alipay_config['alipay_public_key'],$alipay_config['sign_type']);
		$where['order_sn']=$_GET['out_trade_no'];
		$where['order_cn']=$_GET['out_trade_no'];
		$where['_logic'] = 'OR';
		//$order_info=M('order')->where($where)->find();
		if($result) {//验证成功
			$out_trade_no = $_GET['out_trade_no'];//商户订单号
			$trade_no = $_GET['trade_no'];//支付宝交易号
			$status=get_order_status($out_trade_no,'10');
			//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
			if($status){
				$rs=update_order_status($out_trade_no,$trade_no,'20','支付宝');
				if($rs){
					$this->success('订单支付成功','/user/order_info/order/'.$out_trade_no,5);
				}else{
					$this->error('订单支付失败','/user/order_info/order/'.$out_trade_no,5);
				}
				
			}else{
				$this->success('订单支付成功','/user/order_info/order/'.$out_trade_no,5);
			}
		  
			
		}
		else {
			
		    //验证失败
		    //如要调试，请看alipay_notify.php页面的verifyReturn函数
		    $this->error('验证失败','/user/order_info/order/'.$out_trade_no,5);
		  
		}
    }

}
?>
